package catalog;

import java.util.HashMap;
import java.util.Map;

import stalker.Stalker;

public class IDToNameCatalog {
  
  private static final boolean CHECK_REP_ON = true;
  private final Map<Long, String> id_name_bindings;
  
  private void checkRep() {
    assert (id_name_bindings != null) :
      "IDToNameCatalog: field may not be null";
    if (!CHECK_REP_ON) {
      return;
    }
  }
  
  /**
   * Constructs a new stalker unique named catalog
   */
  public IDToNameCatalog() {
    id_name_bindings = new HashMap<Long, String>();
  }
  
  /**
   * Binds a stalker to a name.
   * <p>
   * If already present, replaces it.
   * @requires stalker is not null
   * @param stalker  the new stalker to be added
   * @complexity A(1)
   */
  public synchronized void bind(Stalker stalker, String name) {
    assert stalker != null && name != null;
    
    id_name_bindings.put(stalker.getID(), name);
    checkRep();
  }
  
  /**
   * Checks whether an ID is already contained
   * @requires id is not null
   * @param id  the id that's checked
   * @return true iff id is already present
   * @complexity A(1)
   */
  public synchronized boolean contains(Long id) {
    assert id != null;
    return id_name_bindings.containsKey(id);
  }
  
  /**
   * Retrieves an name given its ID
   * @requires ID is not null, ID is present
   * @param id ID of the Stalker that's being searched in this context
   * @return the name of the stalker whose ID is given in this context
   */
  public synchronized String getNameFromID(Long id) {
    assert (id != null);
    assert (this.contains(id));
    return id_name_bindings.get(id);
  }
  
}
